from schwab_api.auth import SchwabAuth
from schwab_api.client import SchwabClient
import time

auth = SchwabAuth()
client = SchwabClient(auth)

"""
Schwab Market Data API - Example Usage

Demonstrates how to use SchwabAuth and SchwabClient to access
quotes, options, historical data, market hours, movers, and instruments.

Make sure to configure your `config.py` with CLIENT_ID, CLIENT_SECRET, etc.

EX 'Config.py' 

CLIENT_ID = "Schwab App Client ID"
CLIENT_SECRET = "Schwab App Client Secret"
REFRESH_TOKEN = "Refresh Token"
TOKEN_URL = "https://api.schwabapi.com/v1/oauth/token"

Author: Russell Stout 
"""


# ========== QUOTES ==========
print("\n🔹 Real-time quotes for AAPL:")
print(client.get_quotes("AAPL"))

print("\n🔹 Quotes with fundamentals for AAPL & TSLA:")
print(client.get_quotes(["AAPL", "TSLA"], fields="quote,fundamental"))


# ========== OPTIONS ==========
print("\n🔹 Option Chain for AAPL:")
print(client.get_option_chains(symbol="AAPL", strike_count=5, include_underlying_quote=True))

print("\n🔹 Option Expiration Chain for AAPL:")
print(client.get_option_expiration_chain("AAPL"))


# ========== PRICE HISTORY ==========
print("\n🔹 10-day, 1-minute interval chart for AAPL:")
print(client.get_price_history("AAPL"))

print("\n🔹 1-year monthly chart for TSLA, with previous close:")
print(client.get_price_history(
    symbol="TSLA",
    period_type="year",
    period=1,
    frequency_type="monthly",
    frequency=1,
    need_previous_close=True
))

print("\n🔹 7-day custom date range chart for MSFT (1-minute):")
end_ms = int(time.time() * 1000)
start_ms = end_ms - (7 * 24 * 60 * 60 * 1000)
print(client.get_price_history(
    symbol="MSFT",
    frequency_type="minute",
    start_date=start_ms,
    end_date=end_ms
))


# ========== MOVERS ==========
print("\n🔹 Dow Jones Movers:")
print(client.get_movers("$DJI"))

print("\n🔹 NASDAQ Top Gainers (10-minute interval):")
print(client.get_movers("NASDAQ", sort="PERCENT_CHANGE_UP", frequency=10))


# ========== MARKET HOURS ==========
print("\n🔹 Today's Market Hours (Equity + Option):")
print(client.get_market_hours(["equity", "option"]))

print("\n🔹 Forex Market Hours on 2025-07-01:")
print(client.get_market_hours(["forex"], date="2025-07-01"))

print("\n🔹 Today's Hours for Equity Market:")
print(client.get_single_market_hours("equity"))

print("\n🔹 Forex Market Hours on 2025-07-04:")
print(client.get_single_market_hours("forex", date="2025-07-04"))


# ========== INSTRUMENTS ==========
print("\n🔹 Symbol Search for 'TSLA':")
print(client.search_instruments("TSLA", projection="symbol-search"))

print("\n🔹 Fundamental Data for AAPL:")
print(client.search_instruments("AAPL", projection="fundamental"))

print("\n🔹 Description Search for 'Amazon':")
print(client.search_instruments("Amazon", projection="desc-search"))

print("\n🔹 Instrument by CUSIP (Apple Inc.):")
print(client.get_instrument_by_cusip("037833100"))
